/* front.phtml JS  */

$(function () {
	xindm.init();
});
var xindm = {
	/* 初始化 */
	init: function () {
		var s = this;
		s.band();
		s.dealData();
		s.preprocess();
	},
	/* 数据/缓存 */
	"action": null,
	"comicTitle": null, "comicName": null,
	"tempInfo": {}, // 临时漫画信息
	//"history": null, // 阅读历史记录 history[name] => data
	"timeout": 3600 * 24 * 2, // 有效期时间 s // comic数据不适用 15.6.23
	"wpFlag": false, // windows phone os
	"version": '15062702',
	"comicName": "", // 
	"favoriteArr": null, // temp
	"searchArr": null, // temp
	"historyArr": null, // temp
	"userArr": false, // temp
	"timeDiff": false, // 时差
	"hsearchArr": [], //temp
	"searchHistoryTotal": 15, // 保留历史搜索数量
	"searchDATA": {}, // 搜索缓存 search[name][page] => data
	"searchDATA_max": 120, // 搜索缓存 最大记录数
	"DATA": {
		"searchHistory": {}, // 搜索列表
		"syncDate": '', // 上次同步日期
		"update": '', // 
		"comic": {}, // 漫画信息/卷集 缓存 comic[name] => data
		"favorite": {},
		"history": {}, // 阅读历史记录 history[name] => data
		"searchName": '', // 
		//"search": {}, // 搜索缓存 search[name][page] => data // searchDATA
		"fenye": 30, // 搜索列表分页 // [pc]30 [mobile] 20
		"fenyeTwo": 10, // 收藏/历史 分页
		"total": {}, // 当前搜索关键词的记录数
		"searchType": 0 // 搜索路线 [0]pc [1]mobile
	},
	/* 预处理操作 */
	preprocess: function() {
		var s = this;
		var action = $.cookie('action');
		if (typeof action != 'undefined' && action != '') {
			s.action = action;
			switch (action) {
				case 'history':
					var page = $.cookie('page') || 1;
					s.showHistory(page);
					$.cookie('page', '', {expires: -1});
					break;
				default:
					break;
			}
			$.cookie('action', '', {expires: -1});
		}
	},
	/* 数据初始化 */
	dealData: function() {
		var s = this;
		//var timenow = s.getTimenow();
		var version = localStorage.getItem('version') || 0;
		var _data = s.dataMgr('DATA');
		var data = _data || {};
		s.searchDATA = s.dataMgr('searchDATA') || {};
		console.log(s.searchDATA);
		s.DATA = $.extend(s.DATA, data);
		//s.DATA.update = timenow;
		var user = s.dataMgr('user') || false;
		if (typeof user == 'object' && user.user_id > 0) {
			s.userArr = user;
			s.loginProgress();
		}
		//var userAgent = navigator.userAgent;
		//s.wpFlag = /Windows Phone/i.test(userAgent);
		
		// 检查history和favorite是否是对象
		s.historyDeal();
		s.favoriteDeal();
		s.comicDeal();
		s.searchDATADeal();
		s.dealSearchHistory();
		// 版本检查
		version < s.version && s.update(version);
		
	},
	/* 版本更新处理 */
	update: function(version) {
		var s = this;
		localStorage.setItem('version', s.version);
		//return falae;
		var history = s.dataMgr('history') || false;
		if (history) {
			s.DATA.history = $.extend({}, s.DATA.history, history);
			localStorage.removeItem('history');
		}
		s.DATA.fenye = 30;
		s.DATA.searchType = 0;
		//var timenow = s.getTimenow();
		if (version < '15062702' && typeof s.DATA.search != 'undefined') {
			s.searchDATA = s.DATA.search;
			delete s.DATA.search;
			s.dataMgr('searchDATA', s.searchDATA);
		}
		s.dataMgr('DATA', s.DATA);
		//localStorage.clear();
	},
	/* history 数组转对象 */
	historyDeal: function() {
		var s = this;
		timenow = s.getTimenow();
		var historyTemp = {};
		for (var ih in s.DATA.history) {
			if (s.DATA.history[ih] == null || typeof s.DATA.history[ih].comicName == 'undefined') {
				delete s.DATA.history[ih];
				continue;
			}
			if (typeof s.DATA.history[ih].status == 'undefined') {
				s.DATA.history[ih].status = 1;
			}
			historyTemp[ih] = s.DATA.history[ih];
		}
		s.DATA.history = historyTemp;
	},
	/* favorite 数组转对象 */
	favoriteDeal: function() {
		var s = this;
		timenow = s.getTimenow();
		var faovriteTemp = {};
		for (var ir in s.DATA.favorite) {
			if (s.DATA.favorite[ir] == null) {
				continue;
			}
			typeof s.DATA.favorite[ir] != 'object' && (s.DATA.favorite[ir] = {status: s.DATA.favorite[ir], time: timenow});
			faovriteTemp[ir] = s.DATA.favorite[ir];
		}
		s.DATA.favorite = faovriteTemp;
	},
	/* comic 数组转对象 */
	comicDeal: function() {
		var s = this;
		timenow = s.getTimenow();
		var comicTemp = {};
		for (var ic in s.DATA.comic) {
			if (typeof s.DATA.comic[ic] != 'object') {
				continue;
			}
			comicTemp[ic] = s.DATA.comic[ic];
		}
		s.DATA.comic = comicTemp;
	},
	/* 搜索缓存管理 */
	searchDATADeal: function() {
		var s = this;
		var total = 0, del = false;
		for (var i in s.searchDATA) {
			++total;
			if (total > s.searchDATA_max) {
				delete s.searchDATA[i];
				del = true;
			}
		}
		if (del == true) {
			s.dataMgr('searchDATA', s.searchDATA);
		}
	},
	/* 绑定事件 */
	band: function() {
		var s = this;
		$(document).on('keyup', '#cname', function (event) {
			event.keyCode == '13' && $('#search').click();
			return false;
		});
		$(document).on('click', '#clearSearchHistory, #clear-btn, #showSearchHistory, #user_info, #sync, #logout, #do_edit, #do_login, #do_register, #fenye-modif, #search-modif, #user, #about, #setting, #favorite, #history, #read, #search, #confrim, #random, #checkAll, #invert, #reset, #switchVolName', function (event) {
			var id = this.id;
			if (id == 'search') {
				s.searchName();
				//console.log(event);
			} else if (id == 'confrim') {
				s.showVols();
			} else if (id == 'random') {
				s.randomSearch();
			} else if (id == "history") {
				s.showHistory();
			} else if (id == 'favorite') {
				s.showFavorite();
			} else if (id == 'setting') {
				s.showModal('setting');
			} else if (id == 'about') {
				s.showModal('about');
			} else if (id == 'user') {
				s.showModal('user');
			} else if (id == 'fenye-modif') {
				s.fenyeModif();
			} else if (id == 'search-modif') {
				s.searchModif();
			} else if (id == 'do_login') {
				s.loginRegister('login');
			} else if (id == 'do_register') {
				s.loginRegister('register');
			} else if (id == 'do_edit') {
				s.loginRegister('edit_user');
			} else if (id == 'logout') {
				s.logout();
			} else if (id == 'sync') {
				s.syncData();
			} else if (id == 'user_info') {
				s.userInfo();
			} else if (id == 'showSearchHistory') {
				s.showSearchHistory();
			} else if (id == 'clear-btn') {
				s.clearDATA();
			} else if (id == 'clearSearchHistory') {
				s.clearSearchHistory();
			}
			
		});
		/*$('form').submit(function () { // 0.7+版本无效
			// 取消搜索时按回车 触发提交
			if (document.activeElement.id != "sub") {
				//console.log('cancel submit !');
				//return false;
			}
		});*/
		/* 按钮加载状态 */
		$(document).on('click', '[data-loading-text]', function(){
			$(this).button('loading').delay(8000).queue(function() {
				$(this).button('reset');
			});
		});
		/* 阅读/收藏 漫画 */
		$(document).on('click', '[bname], [fav], [delfavorite], [delhistory]', function () {
			// del
			var timenow = s.getTimenow();
			var delhistoryName = $(this).attr('delhistory');
			var delfavoriteName = $(this).attr('delfavorite');
			var _delName = delhistoryName || delfavoriteName;
			var delName = _delName  || null;
			s.DATA = s.dataMgr('DATA'); //
			if (delName != null) {
				if (typeof delhistoryName != 'undefined') {
					//delete s.DATA.history[delName];
					s.DATA.history[delName].status = 0;
					s.DATA.history[delName].time = timenow;
				} else if (typeof delfavoriteName != 'undefined') {
					//delete s.DATA.favorite[delName];
					s.DATA.favorite[delName].status = 0;
					s.DATA.favorite[delName].time = timenow;
				}
				s.dataMgr('DATA', s.DATA);
				$('tr[tname="' + delName + '"]').addClass('hide');
				var total = $('[list-total]:eq(0)').text() - 1;
				$('[list-total]').html(total);
				return true;
			}
			// 
			var parent = $(this).parent();
			var bname = $(this).attr('bname') || null;
			var fav = $(this).attr('fav') || null;
			var comicName = parent.attr('comicName') + '';
			var comicTitle = parent.attr('ntitle') + '';
			s.comicName = comicName;
			s.comicTitle = comicTitle;
			//var res = s.showVols(comicName);
			setTimeout(function() {
				$('button[bname*="' + comicName + '"]').button('reset');
			}, 100);
			/*if (res == false) {
				return false;
			}*/
			
			var type;
			if (bname != null) {
				$('#readComic')[0]['n'].value = comicName;
				$('#readComic').submit();
				//window.open('?a=read&n=' + comicName);
			} else if (typeof fav != null) {
				var _state = fav;
				var state = _state || 0;
				var change = state == 0 ? 1 : 0;
				s.DATA.favorite[comicName] = {"status": change, "time": timenow};
				$(this).attr('fav', change);
				console.log(comicName + ' favorite: ' + change );
			}
			s.dataMgr('DATA', s.DATA);
		});
		/* 注册/登陆/修改 */
		$(document).on('focusout', '[name="user"], [name="user_name"], [name="email"], [name="password"], [name="password4"], [name="password5"], [name="password6"], [name="password1"], [name="password2"]', function() {
			var type = $(this).attr('name');
			var form = $(this).parents('form')[0].id;
			s.getParam(type, form);
		});
		/* 历史搜索 */
		$(document).on('click', '#sh-list li[sh-name]', function() {
			var $dom = $(this);
			var page = $dom.attr('sh-page');
			var searchName = $dom.attr('sh-name');
			
			s.searchName(searchName, page);
		});
	},
	/* 修改分页记录数 */
	fenyeModif: function() {
		var s = this;
		var _fenyeTwo = $('#fenyeTwo').val();
		var fenyeTwo = _fenyeTwo >=1 ? parseInt(_fenyeTwo) + '' : '10';
		s.DATA.fenyeTwo = fenyeTwo;
		s.dataMgr('DATA', s.DATA);
		$('#myModal').modal('hide');
		s.showModal('tips', '成功修改分页数为 <span class="label label-default">' + fenyeTwo + '</span>');
		return true;
	},
	/* 搜索路线 */
	searchModif: function() {
		var s = this;
		var _searchType = $('#searchType').val();
		var searchType = _searchType == 1 ? 1 : 0;
		s.DATA.searchType = searchType;
		s.DATA.fenye = searchType == 1 ? 20 : 30;
		s.searchDATA = {}; // 清空缓存
		s.dataMgr('DATA', s.DATA);
		s.dataMgr('searchDATA', s.searchDATA);
		$('#myModal').modal('hide');
		s.showModal('tips', '搜索线路设置成功');
		return true;
	},
	/* 清除数据 */
	clearDATA: function() {
		var s = this;
		if (window.confirm('你确定要清除吗？')) {
			var type = $('#clearType').val();
			if (type == 'location') {
				localStorage.clear();
				location.reload();
			} else if (type == 'search') {
				s.searchDATA = {};
				s.dataMgr('searchDATA', s.searchDATA);
			} else if (type == 'server') {
				var url = '?c=user_comic&a=clearData';
				$.get(url);
			}
			$('#myModal').modal('hide');
			s.showModal('tips', '清除成功');
			return true;
		}
	},
	/* 搜索列表 */
	showSearch: function(searchName, _page) {
		var s = this;
		var page = typeof _page != 'undefined' && _page > 0 ? parseInt(_page) : 1;
		var data = s.searchDATA[searchName][page], total = data.total;
		s.searchArr = data.lists;
		for (var i in s.searchArr) {
			s.DATA.comic[s.searchArr[i].comicName] || (s.DATA.comic[s.searchArr[i].comicName] = s.searchArr[i]);
		}
		if (page - 0 == 1) {
			s.DATA.total = {'search': searchName, 'total': total};
		} else {
			//console.log(s.DATA.total);
			total = s.DATA.total.total;
		}
		s.searchHistory(searchName, page, total); // 记录关键词
		s.dealLiDom(total, page, 'search');
	},
	/* 阅读历史 */
	showHistory: function(_page) {
		var s = this;
		var page = typeof _page != 'undefined' && _page > 0 ? parseInt(_page) : 1;
		if (page == 1 && s.action != 'history') {
			//location.href = '?action=history&page=' + page;
			$.cookie('action', 'history');
			$.cookie('page', page);
			location.reload();
			console.log('302 history');
			return true;
		} else {
			s.action = '';
		}
		var itemArr = [], total = 0;
		//s.DATA = s.dataMgr('DATA');
		//console.log(s.DATA.history);
		for (var i in s.DATA.history) {
			if (typeof s.DATA.comic[i] != 'object' || typeof s.DATA.comic[i].title == 'undefined') {
				s.showVols(i); // 如无数据则获取
			}
			if (typeof s.DATA.comic[i] != 'object') {
				continue;
			}
			if (s.DATA.history[i].status > 0 && typeof s.DATA.history[i].title != 'undefined') {
				itemArr.push(s.DATA.history[i]);
				++total;
			} else if (typeof s.DATA.history[i].title != 'undefined') {
				delete s.DATA.history[i];
			}
		}
		if (!total) {
			s.showModal('tips', '暂无历史阅读记录');
			return false;
		}
		itemArr.sort(function(a, b) {  
			if(a.time < b.time){
				return 1;
			} else if (a.time > b.time) {
				return -1;
			}
			return 0;
		});
		//itemArr.reverse(); // 反转
		s.historyArr = itemArr;
		s.dealLiDom(total, page, 'history');
	},
	/* 收藏列表 */
	showFavorite: function(_page) {
		var s = this;
		var page = typeof _page != 'undefined' && _page > 0 ? parseInt(_page) : 1;
		s.favoriteArr = [];
		var total = 0;
		for (var i in s.DATA.favorite) {
			if (typeof s.DATA.comic[i] != 'object' || typeof s.DATA.comic[i].title == 'undefined') {
				s.showVols(i); // 如无数据则获取
			}
			if (s.DATA.favorite[i].status == 1) {
				if (typeof s.DATA.comic[i] == 'undefined') { // getVolFlag !== true && 
					continue;
				}
				s.favoriteArr.push(i);
				++total;
			}
		}
		s.favoriteArr.reverse(); // 反转
		s.favoriteArr.sort(function(a, b) {  
			if(a.time < b.time){
				return 1;
			} else if (a.time > b.time) {
				return -1;
			}
			return 0;
		});
		if (!total) {
			s.showModal('tips', '暂无收藏记录');
			return false;
		}
		s.dealLiDom(total, page, 'favorite');
	},
	/* 分页处理 */
	dealPage: function(_page, _total, _flag) {
		var s = this;
		var page = _page > 0 ? _page : 1;
		var total = _total > 0 ? _total : 1;
		var fenye = _flag == 'search' ? s.DATA.fenye : s.DATA.fenyeTwo;
		var pages = Math.ceil(total / fenye);
		if (pages < 2) {
			$('#pages').addClass('hide');
			return false; // 小于两页不显示分页
		}
		var searchName = s.DATA.searchName;
		
		$('#prevPage, #nextPage').removeAttr('disabled'); // 按钮状态复位
		var prevPage = page > 1 ? page - 1 : false;
		var nextPage = page < pages ? page + 1 : false;
		var prevFun, nextFun, listFun;
		if (_flag == 'search') {
			prevFun = 'searchName(\'' + searchName + '\', ' + prevPage + ')';
			nextFun = 'searchName(\'' + searchName + '\', ' + nextPage + ')';
			listFun = 'searchName(\'' + searchName + '\', ';
		} else if (_flag == 'history') {
			prevFun = 'showHistory('+ prevPage + ')';
			nextFun = 'showHistory('+ nextPage + ')';
			listFun = 'showHistory(';
		} else if (_flag == 'favorite') {
			prevFun = 'showFavorite('+ prevPage + ')';
			nextFun = 'showFavorite('+ nextPage + ')';
			listFun = 'showFavorite(';
		}
		prevPage ? $('#prevPage').attr('onclick', 'javascript:void(xindm.' + prevFun + ');') : $('#prevPage').attr('disabled', 'disabled');
		nextPage ? $('#nextPage').attr('onclick', 'javascript:void(xindm.' + nextFun + ');') : $('#nextPage').attr('disabled', 'disabled');
		var pagesDom = [], temp, ii = 0;
		for (var i = 0; i < pages; i++) {
			++ii;
			temp = page == ii ? '<li class="disabled"><a href="#">' + ii + '</a></li>' : '<li><a href="javascript:void(0);" onclick="javascript:void(xindm.' + listFun + ii + '));">' + ii + '</a></li>';
			pagesDom.push(temp);
		}
		var pageStr = pagesDom.join("\n");
		$('#pageList').html(pageStr);
		$('#pageInfo').html(page + '/' + pages);
		$('#pages').removeClass('hide');
		$("[data-toggle='tooltip']").tooltip();
		setTimeout(function() {
			$('#prevPage, #nextPage').button('reset');
		}, 100);
		//location = location.origin + location.pathname + '#' + _flag + page;
	},
	/* make liDom */
	dealLiDom: function (_total, _page, _flag) {
		var s = this;
		var flag = _flag == 'history' ? 'history' : _flag;
		var _data = null;
		var total = _total, data = null;
		var fenye = _flag == 'search' ? s.DATA.fenye : s.DATA.fenyeTwo;
		//alert(fenye);
		if (flag == 'search') {
			_data = s.searchArr || null;
			data = _data;
		} else if (flag == 'history') {
			var startNum = (_page - 1) * fenye;
			var endNum = _page * fenye;
			_data = s.historyArr.slice(startNum, endNum);
			data = _data;
		} else if (flag == 'favorite') {
			var startNum = (_page - 1) * fenye;
			var endNum = _page * fenye;
			_data = s.favoriteArr.slice(startNum, endNum);
			data = _data;
		}
		if (_data == null) {
			s.showModal('tips', '没有记录');
			return false;
		}
		
		// ###
		var linkArr = new Array();
		var imgArr = new Array(); // 临时简介图片
		var fav = 0, author, trigger, name, thumb, title, _state, stateFlag, state, update, brief, link, view, info, tag, favHide = '', delHide = '', delFlag = '';
		for (var i in data) {
			if (flag == 'history') {
				tag = data[i].comicName + '';
				info = s.DATA.comic[tag];
				update = s.DATA.history[tag].rtime;//getLocalTime(s.history[tag].rtime);
				var delRecord = '';
			} else if (flag == 'search') {
				tag = data[i].comicName + '';
				info = s.DATA.comic[tag];
				update = info.update;
				delHide = 'hide';
			} else if (flag == 'favorite') {
				tag = data[i];
				info = s.DATA.comic[tag];//console.log(s.DATA.comic[tag]);
				update = info.update;
				favHide = 'hide';
			}
			//console.log(info);
			thumb = info.thumb;
			name = info.comicName;
			title = decodeURIComponent(info.title);
			_state = decodeURIComponent(info.state);
			stateFlag = _state == '完结' ? '<span class=\'label label-success\'>完结</span>' : '<span class=\'label label-default\'>' + _state + '</span>';
			state = _state == '完结' ? 'class="success"' : '';
			trigger = s.wpFlag ? 'focus' : 'focus hover';
			fav = typeof s.DATA.favorite[name] != 'undefined' && typeof s.DATA.favorite[name].status != 'undefined' ? s.DATA.favorite[name].status : 0;
			brief = decodeURIComponent(info.brief);
			brief = brief.replace(/"/g, '&quot;');
			author = info.author || null;
			author = author != null ? ' 作者: ' + decodeURIComponent(author) : '';
			imgArr.push('<img src="' + thumb + '" />');
			link = '<tr  ' + state + ' tname="' + name + '">';
			view = '<button id="dt_' + name + '" type="button" data-html="true" class="btn btn-default btn-xs" data-container="body" data-toggle="popover" data-trigger="' + trigger + '" title="' + title + author + '" data-placement="right" data-content="' + stateFlag + ' ' + brief + ' <br><img src=\'' + thumb + '\' class=\'img-responsive\'>"><span class="glyphicon glyphicon-info-sign"></span></button>';
			link +='<td class="small text-nowrap text-center">' + view + '</td>';
			link += '<td class="small text-nowrap text-left" title="简介：' + brief + '"><span class="text-info">' + title + '</span></td>';
			link += '<td class="small text-nowrap text-center"><span class="text-muted">' + update + '</span></td>';
			link += '<td class="text-center" ntitle="' + title + '" comicName="' + name + '"><a class="read-act" href="?a=read&n=' + name + '" target="_blank"><button type="button" bname0="' + name + '" autocomplete="on" data-loading-text="Loading..." class="btn btn-default btn-xs" data-toggle="tooltip" data-placement="top" title="阅读"><span class="glyphicon glyphicon-play"></span></button></a><button type="button" fav="' + fav + '" data-toggle="tooltip" data-placement="top" title="收藏" class="btn btn-default btn-xs ' + favHide + '"><span class="glyphicon glyphicon-heart"></span></button><button type="button" del' + flag + '="' + name + '" data-toggle="tooltip" data-placement="top" title="移除" class="btn btn-default btn-xs '+ delHide +'"><span class="glyphicon glyphicon-remove"></span></button></td>';
			link += '</tr>';
			linkArr.push(link);
		}
		var linkDom = linkArr.join('');
		var imgDom = imgArr.join('');
		//_page > 1 && console.log(linkDom);//
		$('#comiclist').html(linkDom);
		$('#img-temp').html(imgDom);
		$('#search-panel, #history-panel, #favorite-panel').addClass('hide');
		$('#' + flag + '-panel').removeClass('hide');
		$('[list-total]').html(total);
		var timeContent = flag == 'history' ? '最近' : '更新';
		$('#thead-update').html(timeContent);
		s.dealPage(_page, total, flag);
		$('#searchList').removeClass('hide'); // 展示搜索内容
		$("[data-toggle='popover']").popover(); // 简介事件
	},
	/* 历史搜索 */
	showSearchHistory: function() {
		var s = this;
		s.dealSearchHistory();
		var $demo = $('#sh-demo'), $dom;
		var hsArr = s.hsearchArr.reverse();
		$('#sh-list li[sh-name]').remove();
		for (var i in hsArr) {
			var searchName = decodeURIComponent(hsArr[i].keyword);
			$dom = $demo.clone();
			$dom.removeClass('hide').attr({"sh-name": hsArr[i].keyword, "sh-page": hsArr[i].page});
			$('[sh-keyword]:eq(0)', $dom).text(' ' + searchName);
			$('[sh-total]:eq(0)', $dom).text(hsArr[i].total);
			$dom.prependTo('#sh-list');
		}
	},
	searchHistory: function(_name, page, total) {
		var s = this;
		var searchName = _name || false;
		if (searchName == false || total < 1) {
			return false;
		}
		var timenow = s.getTimenow();
		if (typeof s.DATA.searchHistory[searchName] != 'undefined') {
			delete s.DATA.searchHistory[searchName];
		}
		s.DATA.searchHistory[searchName] = {"keyword": searchName, "time": timenow, "total": total, "page": page};
		s.dataMgr('DATA', s.DATA);
	},
	dealSearchHistory: function() {
		var s = this;
		var htotal = 0, stotal = 0;
		s.hsearchArr = [];
		for (var i in s.DATA.searchHistory) {
			++htotal;
			s.hsearchArr.push(s.DATA.searchHistory[i]);
		}
		s.hsearchArr.reverse();
		for (var ii in s.hsearchArr) {
			++stotal;
			if (stotal > s.searchHistoryTotal) {
				delete s.DATA.searchHistory[s.hsearchArr.keyword];
				delete s.hsearchArr[ii];
			}
		}
		s.dataMgr('DATA', s.DATA);
	},
	clearSearchHistory: function() {
		var s = this;
		s.hsearchArr = [];
		s.DATA.searchHistory = {};
		s.dealSearchHistory();
	},
	/* 搜索漫画 */
	searchName: function (_name, _page) {
		var s = this;
		var _searchName = _name || $('#cname').val();
		if (_searchName.length < 1) { //  || (/^\w*$/.test(searchName) && searchName.length < 2)
			s.randomSearch();
			return false;
		}
		var searchName_ = decodeURIComponent(_searchName);
		$('#cname').val(searchName_);
		searchName = encodeURIComponent(searchName_); // 搜索关键词
		var page = _page > 0 ? _page : 1; // 页数
		if (searchName != '') {
			s.DATA.searchName = searchName;
			s.searchDATA[searchName] = s.searchDATA[searchName] || []; // 初始化搜索缓存
			s.searchDATA[searchName][page] = s.searchDATA[searchName][page] || [];
			if (typeof s.searchDATA[searchName][page].lists == 'object') {
				var time = s.getTimenow();
				var dtime = s.searchDATA[searchName][page].time || 0;
				if (dtime > 0 && time - dtime < s.timeout) {
					console.log('use cache..');
					setTimeout(function() {
						$("[data-loading-text]").button('reset'); // 按钮状态复位
					}, 100);
					s.showSearch(searchName, page);
					return true;
				}
			}
			var url = '?a=search&searchName=' + searchName + '&page=' + page + '&searchType=' + s.DATA.searchType;
			s.showModal('tips', '正在获取漫画列表，请稍后···'); // 获取动画
			$.get(url, function (_data) {
				$('#myModal').modal('hide'); // 自动关闭 获取动画
				$("[data-loading-text]").button('reset'); // 按钮状态复位
				var data = eval('(' + _data + ')');
				if (typeof data != 'object') {
					s.showModal('tips', '获取数据失败/搜索结果为空');
					return false;
				}
				var status = data.status || 'false';
				if (status != 'false' && data.lists.length > 0) {
					s.searchDATA[searchName][page] = data; // 缓存
					if (page == 1 && data.lists.length < data.total ) {
						s.DATA.fenye = data.lists.length;
					}
					s.dataMgr('DATA', s.DATA); // 本地存储
					s.dataMgr('searchDATA', s.searchDATA); // 本地存储
					s.showSearch(searchName, page);
				} else {
					s.showModal('tips', '无记录');
				}
			});
		}
	},
	/* 随机搜索 */
	randomSearch: function() {
		var s = this;
		var comicNames = s.setComicNames('get');
		var randomComicName = comicNames[Math.floor(Math.random() * comicNames.length)];
		if (comicNames) {
			s.searchName(randomComicName);
		} else {
			var url = '?a=random';
			$.get(url, function (_data, status) {
				var data = eval('(' + _data + ')');
				if (typeof data != 'object' || data.status != 'true') {
					s.showModal('tips', '获取数据失败');
					return false;
				}
				comicNames = data.comicNames;
				var flag = s.setComicNames('save', comicNames);
				s.searchName(randomComicName);
			});
		}
	},
	/* 漫画名全集 */
	setComicNames: function(_flag, _data) {
		var s = this;
		var flag = typeof _flag != 'undefined' && _flag == 'save' ? 'save' : 'get';
		var timenow = s.getTimenow();
		if (flag == 'get') {
			var comicNamesFoo = s.dataMgr('comicNames');
			if (comicNamesFoo == null || timenow - comicNamesFoo.time > 3600 * 24 * 5 || timenow < comicNamesFoo.time) {
				return false;
			}
			console.log('return comicNames');
			return comicNamesFoo.data;
		} else {
			if (typeof _data != 'object') {
				return false;
			}
			var comicNames = {"time": timenow, "data": _data};
			return s.dataMgr('comicNames', comicNames);
		}
	},
	/* 获取卷集列表 */
	showVols: function(_comicName) {
		var s = this;
		var comicName = _comicName || s.comicName;
		// 缓存获取
		var time = s.getTimenow();
		var comic = s.DATA.comic;
		if (typeof comic[comicName] != 'undefined' && comic[comicName] != null && typeof comic[comicName].time != 'undefined' && typeof comic[comicName].title != 'undefined') {
			console.log('use cache..');
			return true;
		}
		// 官网获取
		var url = '?a=showVols&comicName=' + comicName;
		s.showModal('tips', '正在获取漫画信息，请稍后···'); // 获取动画
		var data = s.AJAX(url);
		$('#myModal').modal('hide'); // 自动关闭 获取动画
		if (typeof data.status == 'undefined') {
			s.showModal('tips', '获取结果失败~~');
			return false;
		}
		if (data.status == 'true') {
			s.DATA.comic[comicName] = s.DATA.comic[comicName] || {};
			s.DATA.comic[comicName] = $.extend({}, s.DATA.comic[comicName], data); // 缓存数据
			s.dataMgr('DATA', s.DATA);
			return true;
		} else if (data.status == 'false') {
			s.showModal('tips', '获取列表失败~~');
			return false;
		} else {
			s.showModal('tips', '未知错误');
			return false;
		}
	},
	/* 数据存储管理 */
	dataMgr: function(_name, _data) { // _data = null
		var s = this;
		var data = _data || null;
		var name = _name || null;
		if (_name == null) {
			return false;
		}
		if (data == null) {
			var item = localStorage.getItem(name);
			return JSON.parse(item);
		} else {
			if (name == 'DATA') {
				s.DATA.update = data.update = s.getTimenow();
			}
			
			var itemStr = JSON.stringify(data);
			localStorage.setItem(name, itemStr);
			console.log(name + ' save !');
		}
	},
	/* 显示设置 */
	showSetting: function() {
		$('#settingModal').modal('show');
	},
	/* Ajax */
	AJAX: function(url, post) {
		if (typeof url == 'undefined' || url == '') {
			return false;
		}
		var post = typeof post != 'object' ? post : null;
		var method = post == null ? 'GET' : 'POST';
		var ajax = $.ajax({
			"type": method,
			"url": url,
			"data": post,
			"dataType": 'text',
			"timeout": 15000,
			"async": false,
			"cache": false,
			"success": function (_data) {
				return false;
			}
		});
		if (ajax.status != '200') {
			this.showModal('tips', '请求数据失败，请重试~');
			return false;
		}
		try {
			var json = $.parseJSON(ajax.responseText);
		} catch (err) {
			//var msg = '错误：' + err.message + '\n获取数据失败';
			alert(msg);
		}
		return json;
	},
	/* 提示框 */
	showModal: function(_title, _content) {
		var s = this;
		var title = _title || '^_^';
		if (title == null) {
			return false;
		}
		$('[modal-title], [modal-body]').addClass('hide');
		if (title == 'tips') {
			$('[modal-body="' + title + '"]').html(_content);
		} else if (title == 'setting') {
			$('#fenyeTwo').val(s.DATA.fenyeTwo);
			$('#searchFenye').text(s.DATA.fenye);
			$('#searchType').val(s.DATA.searchType);
		}
		$('[modal-title="' + title + '"], [modal-body="' + title + '"]').removeClass('hide');
		$('#myModal').modal('show');
	},
	/* 获取/校验 参数 */
	getParam: function(_type, _form) {
		var type = _type || 'def';
		var p = {}, wt = '', q = [], data;
		var form = _form || false;
		if (form == false) {
			return false;
		}
		if (form == 'login') {
			p.user = $('[name="user"]').val();
			p.password = $('[name="password"]').val();
		} else if (form == 'register') {
			p.user_name = $('[name="user_name"]').val();
			p.email = $('[name="email"]').val();
			p.password1 = $('[name="password1"]').val();
			p.password2 = $('[name="password2"]').val();
			p.sex = $('[name="sex"]').val() || 0;
		} else if (form == 'edit_user') {
			var password4 = $('[name="password4"]').val();
			if (password4 != '') {
				p.password4 = password4;
				p.password5 = $('[name="password5"]').val();
				p.password6 = $('[name="password6"]').val();
			}
			p.user_id = this.userArr.user_id;
			p.sex3 = $('[name="sex3"]').val() || 0;
		}
		for (var vi in p) {
			p[vi] = $.trim(p[vi]); // 去除空格
		}
		data = p;
		//console.log(data);
		if (type != 'def') {
			q[type] = p[type];
			p = q;
		}
		for (var i in p) {
			var v = p[i];
			switch (i) {
				case 'user':
				case 'user_name':
					var pregUser = i == 'user' ? /^[\w-@\.]{3,30}$/ : /^[\w-]{3,16}$/;
					if (!pregUser.test(data[i])) {
						wt = form == 'login' ? '账户格式不正确' : '账户格式不正确，必须为3至16位的英文数字下划线';
						$('#' + form + ' [name="' + i + '"]').addClass('b-red');
						alert(wt);
					} else {
						$('#' + form + ' [name="' + i + '"]').removeClass('b-red');
					}
					break;
				case 'email':
					var email = data.email;
					var reg = /^.+@.+\..+$/;
					if (email == '' || !reg.test(email)) {
						wt = '邮箱格式不正确';
						alert(wt);
						$('[name="' + i + '"]').addClass('b-red');
					} else {
						$('[name="' + i + '"]').removeClass('b-red');
					}
					break;
				case 'password':
				case 'password1':
				case 'password2':
				case 'password4':
				case 'password5':
				case 'password6':
					var pregPass = /^[a-zA-Z0-9_-]{6,18}$/;
					if (!pregPass.test(data[i])) {
						wt = '密码必须为6至18位的英文数字下划线';
						alert(wt);
						$('[name="' + i + '"]').addClass('b-red');
					} else {
						$('[name="' + i + '"]').removeClass('b-red');
					}
					if ((i == 'password2' && data.password2 !== data.password1) || (i == 'password6' && data.password5 !== data.password6)) {
						$('[name="' + i + '"]').addClass('b-red');
						wt = '两次密码不相等！';
						alert(wt);
					}
					break;
			}
		}
		wt != '' && $('#' + form).focus();
		return wt == '' ? data : false;
	},
	/* 登陆/注册/修改 提交 */
	loginRegister: function(id) {
		if (typeof id == 'undefined') {
			return false;
		}
		var s = this, fmsg, tmsg;
		var p = {};
		p = s.getParam('def', id) || false;
		if (p == false) {
			return false;
		}
		p.c = 'user_comic';
		console.log(p);
		if (id == 'login') {
			p.a = 'login';
			fmsg = '登陆失败,请重试';
			tmsg = '登陆成功';
		} else if (id == 'edit_user') {
			p.a = 'editUser';
			fmsg = '修改失败,请重试';
			tmsg = '修改成功';
		} else if (id == 'register') {
			p.a = 'register';
			fmsg = '注册失败,请重试';
			tmsg = '注册成功';
		}
		var url = '?';
		$.post(url, p, function(data,status) {
			if (typeof data != 'object' || data.status != 'true') {
				s.showModal('tips', data.msg);
			} else {
				s.showModal('tips', data.msg);
				if (id == 'login') {	
					s.userArr = data.user;
					s.dataMgr('user', data.user);
					s.loginProgress(true, true);
				} else if (id == 'edit_user') {
					if (typeof data.login != 'undefined' && data.login == 'false') {
						alert('请重新登录');
						s.loginProgress(false);
					} else if (typeof data.user != 'undefined') {
						s.userArr = $.extend({}, s.userArr, data.user);
						s.dataMgr('user', s.userArr);
					}
				}
			}
		}, 'json');
	},
	/* 登陆处理 */
	loginProgress: function(_flag, _syncFlag) {
		var s = this;
		var flag = _flag || true;
		var syncFlag = _syncFlag == true ? true : false;
		if (flag == false) {
			s.logout();
			return false;
		}
		
		if (typeof s.userArr != 'object' || parseInt(s.userArr.user_id) < 1) {
			return false;
		}
		var url = '?c=user_comic&a=checkLogin';
		$.get(url, function(_data) {
			var data = $.parseJSON(_data);
			if (data.status == 'false') {
				s.logout();
			} else if (data.status == 'true') {
				$('#user').addClass('hide');
				$('#user_info, #sync').removeClass('hide');
				$('#user_name').text(' ' + s.userArr.user_name);
				syncFlag == true && s.syncData(false);
			}
		});
	},
	/* 登出 */
	logout: function() {
		$.cookie('user_id', '');
		$.cookie('user_name', '');
		$.cookie('user_pass', '');
		this.userArr = false;
		this.dataMgr('user', {});
		location.reload();
		return false;
	},
	/* 同步数据 */
	syncData: function(_tips) {
		var s = this;
		var tips = _tips == false ? false : true;
		s.DATA = s.dataMgr('DATA');
		var d = s.DATA;
		var data = {
			comic: d.comic,
			history: d.history,
			favorite: d.favorite,
			fenye: d.fenye,
			fenyeTwo: d.fenyeTwo,
			searchType: d.searchType,
			update: d.update
		};
		var dataStr = encodeURIComponent(JSON.stringify(data));
		var url = '?c=user_comic&a=syncData';
		var p = {"data": dataStr};
		$.post(url, p, function(data) {
			if (data.status == 'true') {
				var sdata = data.data;
				s.DATA.favorite = sdata.favorite;
				s.DATA.history = sdata.history;
				
				s.historyDeal();
				s.favoriteDeal();
				delete sdata.favorite;
				delete sdata.history;
				s.DATA = $.extend({}, s.DATA, sdata);
				s.dataMgr('DATA', s.DATA);
				console.log('sync: success');
				tips && s.showModal('tips', '同步成功'); //
				return true;
			} else {
				s.showModal('tips', '同步失败,请尝试重试'); //
			}
			console.log('sync: failed, status: ' + data.status);
		}, 'json');
	},
	/* 用户信息 */
	userInfo: function() {
		var s = this, u = s.userArr, htotal = ftotal = 0, sex = '未知';
		for (var ih in s.DATA.history) {
			if (s.DATA.history[ih].status > 0 && typeof s.DATA.history[ih].title != 'undefined') {
				++htotal;
			}
		}
		for (var ir in s.DATA.favorite) {
			if (s.DATA.favorite[ir].status == 1) {
				++ftotal;
			}
		}
		switch (u.sex) {
			case '1':
				sex = '男';
				break;
			case '2':
				sex = '女';
				break;
			case '0':
				sex = '未知';
				break;
		}
		$('#user_info_name').text(u.user_name);
		$('#user_info_email').text(u.email);
		$('#user_info_sex').text(sex);
		$('#history_total').text(htotal);
		$('#favorite_total').text(ftotal);
		$('#sync_date').text(s.DATA.syncDate);
		$('[name="sex3"]').val(u.sex);
		s.showModal('user_info');
	},
	/* 获取时间戳 */
	getTimenow: function() {
		var s = this;
		var _timenow = Math.round(new Date().getTime() / 1000);
		if (s.timeDiff === false) {
			s.timeDiff = -(_timenow - window.serverTime);
		}
		var timenow = _timenow + s.timeDiff;
		return timenow;
	},
	/* 获取get参数 */
	getAction: function(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null) return unescape(r[2]);
		return null;
	}
};

// 日期格式化
Date.prototype.Format = function(fmt) { //author: meizz
	// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
	// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
	var o = {
		"M+": this.getMonth() + 1,
		//月份   
		"d+": this.getDate(),
		//日   
		"h+": this.getHours(),
		//小时   
		"m+": this.getMinutes(),
		//分   
		"s+": this.getSeconds(),
		//秒   
		"q+": Math.floor((this.getMonth() + 3) / 3),
		//季度   
		"S": this.getMilliseconds() //毫秒   
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
};